package com.woniuxy.school.dietary.order.controller;


import com.alipay.api.internal.util.AlipaySignature;
import com.woniuxy.commons.core.exception.SchoolException;
import com.woniuxy.commons.core.model.Result;
import com.woniuxy.commons.core.util.JwtUtil;
import com.woniuxy.school.dietary.Dto.OrderDto;
import com.woniuxy.school.dietary.Dto.PageInfoDto;
import com.woniuxy.school.dietary.Dto.findShoppingDto;
import com.woniuxy.school.dietary.from.*;
import com.woniuxy.school.dietary.order.config.AlipayConfiguration;
import com.woniuxy.school.dietary.order.entity.DietOrder;
import com.woniuxy.school.dietary.order.service.DietOrderService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 吴彦祖
 * @since 2025年05月14日
 */
@RestController
@RequestMapping("/dietOrder")
@Api(tags = "膳食管理订单模块")
public class DietOrderController {
    @Resource
    private DietOrderService dietOrderService;
    @Resource
    private AlipayConfiguration alipayConfiguration;
    /**
     * 添加购物车
     */
    @PostMapping("/addShopping")
    @ApiOperation(value ="菜品添加购物车")
    public Result addShopping(@Valid  @RequestBody AddShoppingFrom from, BindingResult br, @RequestHeader String token) throws Exception {
        if (br.hasErrors()){
            throw new SchoolException(503, br.getFieldError().getDefaultMessage());
        }
        Claims claims = JwtUtil.parseUserToken(token);
        Long userId = Long.valueOf(claims.get("userId").toString());
        dietOrderService.addShopping(from, Long.valueOf(userId));
        return Result.getResult().setMessage("添加购物车成功").setCode(200);
    }
    /**
     * 删除购物车
     */
    @PostMapping("/deleteShopping")
    @ApiOperation(value ="删除购物车菜品信息")
    public Result deleteShopping(@Valid @RequestBody DeleteShoppingFrom from, BindingResult br, @RequestHeader String token) throws Exception {
        if (br.hasErrors()) throw new SchoolException(503, br.getFieldError().getDefaultMessage());
        Claims claims = JwtUtil.parseUserToken(token);
        Long userId = Long.valueOf(claims.get("userId").toString());
        dietOrderService.deleteShopping(from,userId);
        return Result.getResult().setMessage("删除购物车成功").setCode(200);
    }
//
    /**
     * 修改购物车数量
     * @param
     * @throws Exception
     */
    @PostMapping("/updateShopping")
    @ApiOperation(value ="修改购物车菜品数量")
    public Result updateShopping(@Valid @RequestBody UpdateShoppingFrom from, BindingResult br, @RequestHeader String token) throws Exception {
       if (br.hasErrors()) throw new SchoolException(503, br.getFieldError().getDefaultMessage());
        Claims claims = JwtUtil.parseUserToken(token);
        Long userId = Long.valueOf(claims.get("userId").toString());
        dietOrderService.updateShopping(from,userId);
        return Result.getResult().setMessage("修改购物车成功").setCode(200);
    }

    /**
     * 查询购物车  分页查询
     * @param
     * @throws Exception
     */
   @PostMapping("/findShopping")
   @ApiOperation(value ="查询购物车菜品信息")
   public Result<findShoppingDto> findShopping(@Valid @RequestBody FindShoppingFrom from, BindingResult br, @RequestHeader String token) throws Exception {
      if (br.hasErrors()) throw new SchoolException(503, br.getFieldError().getDefaultMessage());
       //从token中取出用户id
       Long userId = Long.valueOf(JwtUtil.parseUserToken(token).get("userId").toString());
       findShoppingDto dto=dietOrderService.findShopping(from,userId);
       return Result.getResult(findShoppingDto.class).setData(dto).setMessage("查询购物车成功").setCode(200);
   }

    /**
     * 清空购物车
     */
    @PostMapping("/clearShopping")
    @ApiOperation(value ="清空购物车")
    public Result clearShopping(@RequestHeader String token) throws Exception{
        //从token中取出用户id
        Long userId = Long.valueOf(JwtUtil.parseUserToken(token).get("userId").toString());
        dietOrderService.clearShopping(userId);
    return Result.getResult().setMessage("清空购物车成功").setCode(200);
    }

//
    /**
     * 下单操作
     * @param
     * @throws Exception
     */
    @PostMapping("/addOrder")
    @ApiOperation(value ="下单操作")
    public Result<OrderDto> addOrder(@Valid @RequestBody AddOrderFrom from, BindingResult br,@RequestHeader String token) throws Exception {
       if (br.hasErrors()) throw new SchoolException(503, br.getFieldError().getDefaultMessage());
        //从toke中获取用户id
        String string = JwtUtil.parseUserToken(token).get("userId").toString();
        Long userId = Long.valueOf(string);
        OrderDto dto=dietOrderService.addOrder(from,userId);
        return Result.getResult(OrderDto.class).setMessage("下单成功").setCode(200).setData(dto);
    }
//
    /**
     * 取消订单
     * @param
     * @throws Exception
     */
    @PostMapping("/cancelOrder/{orderNum}")
    @ApiOperation(value ="取消订单")
    public Result cancelOrder(@PathVariable @ApiParam(value = "订单编号") String orderNum) throws Exception {
        //从token中获取用户id

        dietOrderService.cancelOrder(orderNum);
        return Result.getResult().setMessage("取消订单成功").setCode(200);
    }
//
    /**
     * 修改订单详情
     * @param
     * @throws Exception
     */
    @PostMapping("/updateOrder")
    @ApiOperation(value = "修改订单详情")
    public Result updateOrder(@Valid @RequestBody UpdateOrderFrom from, BindingResult br,@RequestHeader String token) throws Exception {
        if (br.hasErrors()) throw new SchoolException(503, br.getFieldError().getDefaultMessage());
        //从token中获取用户id
        Long userId = Long.valueOf(JwtUtil.parseUserToken(token).get("userId").toString());
        dietOrderService.updateOrder(from,userId);
        return Result.getResult().setMessage("修改订单成功").setCode(200);
    }
//
    /**
     * 用户查询我的订单 分页
     * @param
     * @throws Exception
     */
    @PostMapping("/findMyOrder")
    @ApiOperation(value = "用户查询我的订单")
    public Result<PageInfoDto> findMyOrder(@Valid @RequestBody FindMyOrderFrom from, BindingResult br, @RequestHeader String token) throws Exception {
        if (br.hasErrors()) throw new SchoolException(503, br.getFieldError().getDefaultMessage());
        //从token中获取用户id
        Long userId = Long.valueOf(JwtUtil.parseUserToken(token).get("userId").toString());
        PageInfoDto dto=dietOrderService.findMyOrder(from,userId);
        return Result.getResult(PageInfoDto.class).setData(dto).setMessage("查询成功");
    }

    /**
     * 支付
     * @param
     * @throws Exception
     */
    @PostMapping("/pay/{orderNum}")
    @ApiOperation(value = "发起支付")
     public Result<String> pay(@PathVariable String orderNum,@RequestHeader String token) throws Exception {
         //从token中获取用户id
         Long userId = Long.valueOf(JwtUtil.parseUserToken(token).get("userId").toString());
        //发起支付成功会返回前端一个表单页面
         String pay = dietOrderService.pay(orderNum,userId);
         return Result.getResult(String.class).setMessage("发起支付成功").setCode(200).setData(pay);
     }
//
    /**
     * 支付成功的回调函数
     * @param
     * @throws Exception
     */
      @PostMapping("/notify")
      @ApiOperation(value = "支付成功回调函数")
      public String callBack(HttpServletRequest request) throws Exception {
          System.out.println("进入回调函数");
          //拿到支付宝返回的参数
          //使用map保存参数
          Map<String, String> params = new HashMap<>();
          Map<String, String[]> map = request.getParameterMap();
          Iterator<String> iterator = map.keySet().iterator();

          while (iterator.hasNext()) {
              //每一个参数的key
              String key = iterator.next();
              //根据key获取参数值
              String[] values = map.get(key);
              String valueStr = "";
              //拿到的value可能存在多个值 因此遍历他 如果存在多个值 用字符串拼接放进map
              for (int i = 0; i < values.length; i++) {
                  valueStr = (i == values.length - 1) ? valueStr + values[i]
                          : valueStr + values[i] + ",";
              }
              params.put(key, valueStr);
          }
          System.out.println(params);
          //在异步回调业务层验签 防止伪造请求
          boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfiguration.getAlipayPublicKey(),"utf-8", "RSA2");
          //根据验签结果判断是否是支付宝发来的请求
          if (!signVerified){
              return "failure";
          }
          //判断订单是否已经支付成功
          if(!params.get("trade_status").equals("TRADE_SUCCESS")){
              return "failure";
          }
          //获取订单编号
          String orderNum =params.get("out_trade_no");
          //获取支付时间
          String payment = params.get("gmt_payment");
          String callBack =dietOrderService.callBack(orderNum,payment);
          return "success";
      }
//
    /**
     * 商户查询单个订单详情
     * @param
     * @throws Exception
     *
     */
    @PostMapping("/storeFindOrder")
    @ApiOperation(value = "商户查询单个订单详情")
    public  Result<PageInfoDto> storeFindOrder(@Valid @RequestBody StoreFindOrderFrom from, BindingResult br, @RequestHeader String token) throws Exception {
        if (br.hasErrors()) throw new SchoolException(503, br.getFieldError().getDefaultMessage());
        //从token中获取商户id
        Long storeId = Long.valueOf(JwtUtil.parseUserToken(token).get("userId").toString());
        PageInfoDto dto=dietOrderService.storeFindOrder(from,storeId);
        return Result.getResult(PageInfoDto.class).setData(dto).setMessage("查询成功").setCode(200);
    }
    /**
     * 根据订单编号查询订单详情
     */
    @GetMapping("/findOrderByOrderNum/{orderNum}")
    @ApiOperation(value = "根据订单编号查询订单详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderNum", value = "订单编号", paramType = "path")})
    public Result<DietOrder> findOrderByOrderNum(@PathVariable String orderNum) throws Exception {
        DietOrder dietOrder = dietOrderService.findOrderByOrderNum(orderNum);
        return Result.getResult(DietOrder.class).setData(dietOrder).setMessage("查询成功").setCode(200);
    }
//
//
//
//      public static void main(String[] args) throws Exception {
//        System.out.println(JwtUtil.parseUserToken("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE3NDczMTAyMjN9.QRo1lGXnEsuG48IXICTGA5LMNXOiCeECCrp1QauRS29m95qyT0jJxg-MfNb5pg18QmjJe831UnPIAez8Wtqbpg"));
//    }




}

